package org.byqh.dqeai.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.byqh.dqeai.common.Json;
import org.byqh.dqeai.dto.SysFavoriteShareDTO;
import org.byqh.dqeai.entity.SysFavoriteShare;
import org.byqh.dqeai.entity.proxy.SysFavoriteShareProxy;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/sysFavoriteShare")
@Tag(name = "系统[SysFavoriteShare] - 收藏共享管理")
public class SysFavoriteShareController extends BaseController<SysFavoriteShare, SysFavoriteShareProxy> {
    /**
     * 分页查询数据
     */
    @PostMapping(value = "/list")
    public Json<List<SysFavoriteShare>> listAll(
            @RequestBody(required = false) SysFavoriteShareDTO dto) {

        return this.listImpl(SysFavoriteShare.class, (query) -> {
            if (dto != null) {
                if (!StringUtils.isBlank(dto.getUserId())) {
                    String subquery = String.format(
                            "select role_id from EAI_SYS_USER_ROLE t where user_id='%s'",
                            dto.getUserId());

                    query = query.where(o -> o.or(() -> {
                        o.roleId().in(easyQueryClient.queryable(subquery, String.class));
                        o.userId().eq(dto.getUserId());
                    }));
                } else if (!StringUtils.isBlank(dto.getFavId())) {
                    query = query.where(o -> o.favId().eq(dto.getFavId()));
                }
            }

            return query;
        });
    }

    /**
     * 删除数据
     */
    @PostMapping(value = "/delete")
    public Json<Boolean> delete(@RequestBody SysFavoriteShareDTO dto) {
        try {
            if (dto.getIdList() == null || dto.getIdList().isEmpty()) {
                return Json.error();
            }

            var rows = this.getEntityDeletable()
                    .where(s -> s.id().in(dto.getIdList()))
                    .executeRows();

            return rows > 0 ? Json.success() : Json.error();
        } catch (Exception ex) {

            return Json.exception(ex);
        }
    }
}